<!--  -->
<template>
  <div class="domainBox">
    <el-form style="margin-top:24px;" :inline="true" :model="formInline" class="demo-form-inline"
      onsubmit="return false;" @submit.native.prevent>
      <el-form-item label="绑定域名">
        <el-input size="small" style="width:360px;" v-model="formInline.domain" placeholder="输入域名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="small" type="primary" @click="onSubmit">绑&nbsp;定</el-button>
      </el-form-item>
      <el-form-item v-if="beianLink">
        <a :href="beianLink" target="_blank"  class="btn-ato">提交备案</a>
      </el-form-item>
      <el-form-item>
        <a :href="domainShopLink" target="_blank" v-if="!isAgent"  class="btn-org">购买域名</a>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" size="medium" :data="domainData" border style="width: 100%">
      <el-table-column header-align="center" prop="domainName" label="域名" :resizable="false">
      </el-table-column>
      <el-table-column header-align="center" align="center" prop="domainType" width="120" label="类型" :resizable="false">
      </el-table-column>
      <el-table-column header-align="center" align="center" prop="statusString" label="状态" :resizable="false">
        <template slot-scope="scope">
          <span v-html="scope.row.statusString"></span>
          <!-- <a :href="beianLink" target="_blank" v-if="scope.row.status === 2 && beianLink" class="btn-a">提交备案</a> -->
        </template>
      </el-table-column>
      <el-table-column header-align="center" align="center" prop="policeRecord" label="公安备案号" :resizable="false">
        <template slot-scope="scope">
          {{scope.row.policeRecord ? scope.row.policeRecord : '--'}}
        </template>
      </el-table-column>
      <el-table-column width="220" header-align="center" align="center" fixed="right" label="操作" :resizable="false">
        <template slot-scope="scope">
          <el-button @click="editRecord(scope.row)" v-if="scope.row.type === 1" type="text" size="small">编辑备案号</el-button>
          <el-button @click="access(scope.row)" type="text" size="small">访问</el-button>
          <el-button @click="code(scope.row)" v-if="scope.row.type === 1" type="text" size="small">二维码</el-button>
          <el-button @click="deleteitem(scope.row)" v-if="scope.row.type === 1" type="text" size="small">删除</el-button>
          <el-button @click="changPsw(scope.row)" v-if="scope.row.type === 0" type="text" size="small">编辑访问密码</el-button>
          <el-button @click="share(scope.row)" v-if="scope.row.type === 0" type="text" size="small">分享</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="二维码" :visible.sync="dialogVisible" :close-on-click-modal="false">
      <el-form style="" :inline="true" class="demo-form-inline" onsubmit="return false;">
        <el-form-item label="链接" style="margin-bottom: 2px;">
          <el-input size="small" style="width:360px;" v-model="qrcodeLink" placeholder="http:// 或者 https:// 开头">
          </el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 2px;">
          <el-button size="small" type="primary" @click="makeQrcode">生 成</el-button>
        </el-form-item>
      </el-form>
      <div class="qrcode">
        <el-image :src="qrcodesrc" :fit="'cover'" @load="() => {qrdownload = true}" @error="() => {qrdownload = false}">
          <div slot="placeholder" class="image-slot">
            制作中<span class="dot">...</span>
          </div>
          <div slot="error" class="image-slot">
            输入需要生成二维码的链接<span class="dot">...</span>
          </div>
        </el-image>
      </div>
      <a ref="qra" href="" download="" style="display: none;"></a>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false" size="small">取 消</el-button>
        <el-button :disabled="!qrdownload" type="primary" @click="downloadQrcode" size="small">下 载</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑备案号" :visible.sync="dialogFormVisible" :width="'480px'" :close-on-click-modal="false">
      <el-form v-loading="formLoading" :model="form">
        <el-form-item label="网站域名" :label-width="formLabelWidth" >
          <el-input size="medium" v-model="form.domainName" disabled></el-input>
        </el-form-item>
        <el-form-item label="公安备案号" :label-width="formLabelWidth" >
            <el-input size="medium" v-model="form.policeRecord" maxlength="127"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogFormVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="submitPoliceRecord">确 定</el-button>
        </div>
    </el-dialog>

    <el-dialog title="便捷访问指引" :visible.sync="dialogRedirctVisible" :width="'480px'" :close-on-click-modal="false">
      <div>
        <p style="margin-bottom:10px;">您已成功绑定域名，添加系统域名重定向可获得更友好的访问体验</p>
        <p>本操作将您的系统域名<span>“{{sysDomain}}”</span>重定向至<br/><span>“{{firstDomain}}”</span>的记录</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="submitRedirctAdd">添加</el-button>
        <el-button size="small" @click="dialogRedirctVisible = false">以后再说</el-button>
      </div>
    </el-dialog>

    <el-dialog title="编辑系统域名访问密码" :visible.sync="dialogFormPswVisible" :width="'480px'" :close-on-click-modal="false">
      <el-form v-loading="formPswLoading" :model="formPsw">
        <el-form-item label="系统域名" :label-width="formLabelWidth" >
          <el-input size="medium" v-model="formPsw.domainName" disabled></el-input>
        </el-form-item>
        <el-form-item label="访问密码" :label-width="formLabelWidth" class="requireStar" >
            <el-input size="medium" v-model="formPsw.password" maxlength="127"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button size="small" @click="dialogFormPswVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="submitPassword">确 定</el-button>
        </div>
    </el-dialog>

    <el-dialog title="分享" :visible.sync="dialogFormShareVisible" :width="'480px'" :close-on-click-modal="false">
      <div v-loading="formShareLoading" class="shareText">
        <p>系统域名：http://{{formShare.domainName}}</p>
        <p>访问密码：{{formShare.password}}</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogFormShareVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="copy">复制</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import * as WindowType from '@/config/windowtype.js'// 公共方法
import * as PubsubType from '@/config/pubsubtype.js'
import * as DesignFunctions from '@/core/DesignFunctions.js'
import PubSub from 'pubsub-js'
import * as functions from '@/core/functions.js'
var _ = require('lodash')
export default {
  created () {
    this.resetData()
    // 请求备案链接
    this.$post('/host/beian-link').then(
      response => {
        if (response) {
          this.beianLink = response
        } else {
          this.beianLink = ''
        }
      },
      error => {
        console.error(error)
      }
    )
    // 是否代理商
    functions.agentInfo().then(agent => {
      if (parseInt(agent.loginAgentDomain) === 1) {
        this.isAgent = true
      } else {
        this.isAgent = false
      }
    })
  },
  data () {
    return {
      formInline: {
        domain: ''
      },
      domainData: [],
      loading: false,
      // 二维码
      dialogVisible: false,
      // 二维码链接
      qrcodeLink: '',
      // 二维码图片地址
      qrcodesrc: '',
      // 二维码是否可以下载
      qrdownload: false,
      beianLink: '',
      // 编辑备案号
      form: {},
      formLabelWidth: '100px',
      dialogFormVisible: false,
      formLoading: false,
      dialogRedirctVisible: false,
      sysDomain: '',
      sysDomainId: 0,
      firstDomain: '',
      firstDomainId: 0,
      // 编辑系统域名访问密码
      formPsw: {
        domainName: '',
        password: ''
      },
      dialogFormPswVisible: false,
      formPswLoading: false,
      // 分享复制
      formShare: {
        domainName: '',
        password: ''
      },
      dialogFormShareVisible: false,
      formShareLoading: false,
      // 购买跳转
      domainShopLink: 'https://www.35.cn/services/domain/',
      isAgent: true
    }
  },
  methods: {
    resetData () {
      this.loading = true
      this.$post('/domain/infos-list').then(response => {
        if (response && response.length > 0) {
          this.domainData = initData(response)
        } else {
          this.domainData = []
        }
        this.loading = false
      })
    },
    onSubmit () {
      this.formInline.domain = this.formInline.domain.replace(/^\s*|\s*$/g, '')
      // 绑定域名
      if (!this.formInline.domain) {
        this.$message.error('请输入域名！')
        return
      }
      if (this.formInline.domain.length > 100) {
        this.$message.error('请输入100个字符以内的域名！')
        return
      }
      if (!/^[a-zA-Z0-9\u4e00-\u9fa5][-a-zA-Z0-9\u4e00-\u9fa5]{0,62}(\.[a-zA-Z0-9\u4e00-\u9fa5][-a-zA-Z0-9\u4e00-\u9fa5]{0,62})+\.?$/.test(this.formInline.domain)) {
        this.$message.error('输入的域名格式不匹配！')
        return
      }
      this.loading = true
      this.$post('/domain/bind', { domain: this.formInline.domain }).then(response => {
        if (response && response.length > 0) {
          if (parseInt(response.length) === 2) {
            this.$post('/domain/redirect-alert').then(response => {
              if (response === 1) {
                this.dialogRedirctVisible = true
              }
            })
            for (let i = 0; i < response.length; i++) {
              if (parseInt(response[i].domainType) === 0) {
                this.sysDomain = response[i].domainName
                this.sysDomainId = response[i].id
              } else {
                this.firstDomain = response[i].domainName
                this.firstDomainId = response[i].id
              }
            }
          }
          this.domainData = initData(response)
          this.formInline.domain = ''
        }
        this.loading = false
      })
    },
    submitRedirctAdd () {
      // 请求设置 301
      this.$post('/domain/bind-redirect', { id: this.sysDomainId, redirectId: this.firstDomainId }).then(response => {
        if (response && parseInt(response) > 0) {
          PubSub.publish(PubsubType.PUBSUB_DELETE_DOMAIN_PUSH)
        }
        this.dialogRedirctVisible = false
      })
    },
    editRecord (data) {
      this.dialogFormVisible = true
      this.formLoading = true
      this.form = JSON.parse(JSON.stringify(data))
      this.formLoading = false
    },
    submitPoliceRecord () {
      this.formLoading = true
      this.$post('/domain/update-police-record', { policeRecord: this.form.policeRecord, id: this.form.id }).then(response => {
        if (response) {
          this.resetData()
          this.dialogFormVisible = false
        }
        this.formLoading = false
      })
    },
    access (data) {
      // window.open('http://' + data.domainName + '/')
      if (data.type === 0) {
        this.$post('/url/site-link').then(response => {
          if (response) {
            window.open(response, '_blank')
          }
        })
      } else {
        window.open('http://' + data.domainName + '/')
      }
    },
    code (data) {
      // 弹出获取二维码并且可下载
      this.dialogVisible = true
      this.qrcodeLink = 'http://' + data.domainName + '/'
      this.makeQrcode()
    },
    deleteitem (data) {
      this.$confirm('确定要删除 ' + data.domainName + ' 域名吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除域名
        this.loading = true
        this.$post('/domain/delete-item', { id: data.id }).then(response => {
          if (response && parseInt(response.id) === parseInt(data.id)) {
            let index = this.domainData.findIndex(element => {
              return parseInt(element.id) === parseInt(response.id)
            })
            if (index > 0) {
              this.domainData.splice(index, 1)
              PubSub.publish(PubsubType.PUBSUB_DELETE_DOMAIN_PUSH)
            }
          }
          this.loading = false
        })
      }).catch(() => {
      })
    },
    makeQrcode () {
      let qrcodeLink = _.trim(this.qrcodeLink)
      if (qrcodeLink.indexOf('http://') === 0 || qrcodeLink.indexOf('https://') === 0 || qrcodeLink.indexOf('//') === 0) {
        let src = DesignFunctions.getDesignPath(this.$store.state.host.id, this.$store.state.site.site.id, '/html/qrcode.html')
        this.qrcodesrc = src + '?qr=' + decodeURI(qrcodeLink)
        return
      }
      this.$message.warning('输入的链接请以 http://、https://、// 这三种方式开头！')
    },
    downloadQrcode () {
      let a = this.$refs['qra']
      var event = new MouseEvent('click')
      a.download = '二维码'
      a.href = this.qrcodesrc
      a.dispatchEvent(event)
    },
    changPsw (data) {
      this.dialogFormPswVisible = true
      this.formPswLoading = true
      this.formPsw.domainName = data.domainName
      this.$post('/host/sysdomain-access-token').then(response => {
        if (response) {
          this.formPsw.password = response
        }
        this.formPswLoading = false
      })
    },
    submitPassword () {
      if (!this.formPsw.password.trim()) {
        this.$message.error('系统域名密码不能为空！')
        return
      }
      let token = this.formPsw.password.trim()
      this.$post('/host/update-sysdomain-access-token', {token: token}).then(response => {
        if (response) {
          this.$message.success('修改成功！')
          this.dialogFormPswVisible = false
        }
      })
    },
    share (data) {
      this.dialogFormShareVisible = true
      this.formShareLoading = true
      this.formShare.domainName = data.domainName
      this.$post('/host/sysdomain-access-token').then(response => {
        if (response) {
          this.formShare.password = response
        }
        this.formShareLoading = false
      })
    },
    copy () {
      let copyText = '系统域名：http://' + this.formShare.domainName + '\r\n'
      copyText = copyText + '访问密码：' + this.formShare.password + '\r\n'
      const input = document.createElement('textarea')
      document.body.appendChild(input)
      input.innerHTML = copyText
      input.setAttribute('code', 1)
      input.select()
      if (navigator.clipboard !== undefined) { // Chrome
        navigator.clipboard.writeText(copyText).then(() => {
          this.$message.success('复制成功！')
        }, function (err) {
          console.error('Async: Could not copy text: ', err)
        })
      } else if (window.clipboardData) { // Internet Explorer
        window.clipboardData.setData('Text', copyText)
        this.$message.success('复制成功！')
      } else {
        document.execCommand('Copy')
        let list = document.getElementsByTagName('textarea')
        let inputList = Array.prototype.slice.call(list)
        inputList.forEach((item) => {
          if (item.getAttribute('code')) {
            document.body.removeChild(item)
          }
        })
        this.$message.success('复制成功！')
      }
      this.dialogFormShareVisible = false
    }
  }
}

function initData (response) {
  return response.map(element => {
    let remark
    remark = element.remark ? JSON.parse(element.remark) : ''
    let statusString
    if (parseInt(element.status) === 0) {
      statusString = '未审核'
    } else if (parseInt(element.status) === 1) {
      statusString = '已备案' + (remark.recordinfo ? '（' + remark.recordinfo + '）' : '')
    } else if (parseInt(element.status) === 2) {
      statusString = '<span class="orange">未备案</span>'
    } else {
      statusString = '未知'
    }
    return {
      id: element.id,
      domainName: element.domainName,
      type: parseInt(element.domainType),
      domainType: parseInt(element.domainType) === 0 ? '系统默认' : '用户绑定',
      status: parseInt(element.status),
      statusString: statusString,
      policeRecord: element.policeRecord,
      remark: remark
    }
  })
}

</script>
<style scoped lang="scss">
.domainBox /deep/ .el-table th {
  background: #eff1f8;
  color: #555;
  border-color: #fff;
}
.domainBox /deep/ .el-table__fixed-right{
  height: 100% !important;
}
.qrcode {
  width: 280px;
  height: 280px;
  margin: 12px auto 0;
}

.qrcode .el-image {
  width: 100%;
  height: 100%;
}

.qrcode .el-image .image-slot {
  display: flex;
  line-height: 280px;
  justify-content: center;
  background-color: #eeeeee;
  color: #858585;
}
.btn-a {
  font-size: 12px;
  margin-left: 5px;
}
.btn-ato {
  padding: 9px 20px;
  background: #67C23A;
  font-size: 12px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
  color: #fff;
  &:hover{
    opacity: 0.8;
  }
}
.requireStar /deep/ .el-form-item__label:before {
  content: '*';
  color: #f56c6c;
  margin-right: 4px;
}
.shareText p{
  margin-bottom: 10px;
}
.btn-org{
  padding: 9px 20px;
  background: #E6A23C;
  font-size: 12px;
  -webkit-border-radius: 2px;
  border-radius: 2px;
  color: #fff;
  &:hover{
    opacity: 0.8;
  }
}
</style>
